package com.cxy.impl;

import com.alibaba.fastjson.JSONObject;
import com.aliyuncs.CommonRequest;
import com.aliyuncs.CommonResponse;
import com.aliyuncs.DefaultAcsClient;
import com.aliyuncs.IAcsClient;
import com.aliyuncs.exceptions.ClientException;
import com.aliyuncs.http.MethodType;
import com.aliyuncs.profile.DefaultProfile;
import org.springframework.stereotype.Service;

import java.util.Map;

@Service
public class SendSmsImpl implements SendSms {
    /**
     * 发送短信
     * @param PhoneNumbers 手机号
     * @param TemplateCode 模板code
     * @param code 参数
     * @return
     */
    @Override
    public boolean send(String PhoneNumbers, String TemplateCode, Map<String, Object> code) {
        DefaultProfile profile = DefaultProfile.getProfile("cn-hangzhou", "<accessKeyId>", "<secret>");
        IAcsClient client = new DefaultAcsClient(profile);

        // 构建请求
        CommonRequest request = new CommonRequest();
        request.setSysMethod(MethodType.POST);
        request.setSysDomain("dysmsapi.aliyuncs.com"); // 不要动
        request.setSysVersion("2017-05-25"); // 不要动
        request.setSysAction("SendSms");

        // 自定义参数（手机号，验证码，签名，模板）
        request.putQueryParameter("PhoneNumbers", PhoneNumbers);
        request.putQueryParameter("SignName", "xxx"); // 手机号
        request.putQueryParameter("TemplateCode", TemplateCode); // 签名
        request.putQueryParameter("TemplateParam", JSONObject.toJSONString(code)); // 模版Code
        try {
            CommonResponse response = client.getCommonResponse(request);
            System.out.println(response.getData());
            return response.getHttpResponse().isSuccess();
        } catch (ClientException e) {
            e.printStackTrace();
        }
        return false;
    }
}
